package model.arbolBSharp;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;


public class ConversorBytesTexto extends ConversorBytes{
	
	private Integer cantidadAConvertir;
	private List<String> listaStrings;
	
	public Integer getCantidadAConvertir() {
		return cantidadAConvertir;
	}
	public void setCantidadAConvertir(Integer cantidadAConvertir) {
		this.cantidadAConvertir = cantidadAConvertir;
	}
	public List<String> getListaStrings() {
		return listaStrings;
	}
	public void setListaStrings(List<String> listaStrings) {
		this.listaStrings = listaStrings;
	}
	@Override
	public void convertirAObjetos(InputStream input) throws IOException {
		if (input == null)
			throw new NullPointerException("input");
		
		if (cantidadAConvertir==null)
			throw new NullPointerException();
		
		int i = cantidadAConvertir;
		
		listaStrings = new ArrayList<String>(cantidadAConvertir);
		
		while(i>0){
			i--;
			
			int largoPalabra = input.read();
			
			byte[] arrayBytes = new byte[largoPalabra];
			input.read(arrayBytes);
			String nuevaPalabra = new String(arrayBytes);
			
			listaStrings.add(nuevaPalabra);
		}		
	}
	
	@Override
	public void convertirABytes(OutputStream output) throws IOException {
		if (output == null)
			throw new NullPointerException("output");
		
		if(listaStrings==null)
			throw new NullPointerException();
		
		if (listaStrings.size() == 0)
			return;
		
		for(String palabra : listaStrings){
			output.write(palabra.length());
			output.write(palabra.getBytes(), 0, palabra.length());
		}
	}
}
